import {Message} from "element-ui";
import {getTierAll, getUserMenus} from "@/api/menus";
import VueRouter from "vue-router";
import routers from "@/router";


export const initMenu = (router, store) => {

    //获取菜单信息
    getUserMenus()
        .then(res => {
            if (res) {
                //格式化路由信息
                let fmtRoutes = formatRoutes(res.data);
                store.dispatch("setMenuList", res.data);
                if (router.getRoutes().length <= 4) {
                    fmtRoutes.forEach(item => {
                        router.addRoute(item);
                    })
                }
            } else {
                if (res) {
                    Message({type: 'error', message: res.message});
                }
            }
        });
};

export const formatRoutes = (menus) => {
    let fmtMenus = [];
    menus.forEach(menu => {
        //抽取出部分属性
        let {
            id,
            menuName,
            path,
            icon,
            component,
            children,
        } = menu;

        //递归遍历
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }

        let fmtRoute = {
            id: id,
            name: menuName,
            path: path,
            icon: icon,
            children: children,
            component(resolve) {
                if (component !== 'Layout') {
                    require(['../views' + component.toLowerCase()], resolve);
                } else {
                    require(['../components/Layout/home'], resolve);
                }
            }
        };
        fmtMenus.push(fmtRoute);
    });
    return fmtMenus;
};
